package net.kylewu;

import java.io.IOException;

import javax.swing.JTextArea;

import net.kylewu.object.FanfouMessage;

import org.dom4j.DocumentException;

/**
 * 
 * @author Kyle Wu
 *
 */
public class ThreadRunner extends Thread {

	private JTextArea jTextArea;
	private RCFFProperties rcffProperties;
	private RCFFCommands rcffCommands;

	public ThreadRunner(RCFFProperties rcffProperties,
			RCFFCommands rcffCommands, JTextArea jTextArea) {
		this.rcffProperties = rcffProperties;
		this.rcffCommands = rcffCommands;
		this.jTextArea = jTextArea;
	}

	public void run() {
		try {

			FanfouMessage ffm = getLatestMessage();

			// TODO check is text is new
			String sysCommand = rcffCommands.getSystemCommand(ffm.getText());

			if (sysCommand != null) {
				Runtime.getRuntime().exec(sysCommand);
			} else {
				jTextArea.append("Illegal command.\n");
			}

		} catch (InterruptedException e) {
			jTextArea
					.append("It has already been set to stop getting messages from fanfou.\n");
		} catch (IOException e) {
			jTextArea.append("Error occurs while running command.\n");
		} catch (DocumentException e) {
			jTextArea.append("Cannot connect to fanfou.com right now.\n");
		}

	}

	private FanfouMessage getLatestMessage() throws InterruptedException,
			DocumentException {

		FanfouMessage ffm = RCFFMessageReader.getLatestMessage(rcffProperties
				.getUrl()
				+ rcffProperties.getUsername());

		if (this.isInterrupted()) {
			throw new InterruptedException();
		}

		return ffm;

	}
}
